package pcb 
{
	import com.gskinner.motion.GTweeny;
	import com.intel.core.Application;
	import com.intel.utils.Debugger;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import gs.easing.Sine;
	
	/**
	 * ...
	 * @author Fintan Boyle
	 */
	public class Preloader extends Application 
	{
		private var loadingScreen:MovieClip;
		
		public function Preloader() 
		{
			addEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
			// show loader
			loadingScreen = this.getChildByName("startupLoadingScreen") as MovieClip;
			
		}
		
		private function progress(e:ProgressEvent):void 
		{
			// update loader
		}
		
		private function checkFrame(e:Event):void 
		{
			if (currentFrame == totalFrames) 
			{
				removeEventListener(Event.ENTER_FRAME, checkFrame);
				
				hideLoadScreen();
				
				applicationWidth = this.width;
				applicationHeight = this.height;

				startup();
			}
		}
		
		private function hideLoadScreen():void
		{
			loadingScreen.cacheAsBitmap = true; //so that text also fades out
			var time:int = 2.5;
			var gTween:GTweeny = new GTweeny(loadingScreen, time, null, { ease:Sine.easeInOut } );
			gTween.setProperty("alpha", 0);
			var t:Timer = new Timer(time,1);
			t.addEventListener(TimerEvent.TIMER_COMPLETE, t_onComplete);
			t.start();
			
		}
		
		private function t_onComplete(e:TimerEvent):void 
		{
			if (Timer(e.target).currentCount == Timer(e.target).repeatCount) {
				Debugger.traceOut("pcb.Preloader >>  loadingScreen removed");
				//removeChild(loadingScreen);
				loadingScreen = null;
				e.target.stop();
				e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, t_onComplete);
			}
		}
		
		private function startup():void 
		{
			// hide loader
			stop();
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			addChild(new pcb.Main());
			
			var loaderScreen:MovieClip = MovieClip(Application.root).getChildByName("startupLoadingScreen") as MovieClip;
			//have it on top of everything
			removeChild(loaderScreen);
			addChild(loaderScreen);
			
		}
		
	}
	
}